
package com.platform.api.bzproject.controller;

import com.platform.api.bzproject.dto.UserDto;
import com.platform.api.bzproject.dto.UserMoney;
import com.platform.api.bzproject.dto.UserPassword;
import com.platform.api.bzproject.model.User;
import com.platform.api.bzproject.param.UserInfoParam;
import com.platform.api.bzproject.service.UserService;
import com.platform.common.core.Result;
import com.platform.common.util.CacheManagerUtil;
import com.platform.common.util.EncryptionUtil;
import com.platform.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.*;


import cn.hutool.extra.emoji.EmojiUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@RestController
@RequestMapping("/p/user")
@Api(tags = "用户接口")
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    private final MapperFacade mapperFacade;

    private final CacheManagerUtil cacheManagerUtil;

    private final ConsumerTokenServices consumerTokenServices;

    /**
     * 查看用户接口
     */
    @GetMapping("/userInfo")
    @ApiOperation(value = "查看用户信息", notes = "根据用户ID（userId）获取用户信息")
    public ResponseEntity<UserDto> userInfo() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        UserDto userDto = mapperFacade.map(user, UserDto.class);
        return ResponseEntity.ok(userDto);
    }

    @PutMapping("/setUserInfo")
    @ApiOperation(value = "设置用户信息", notes = "设置用户信息")
    public ResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = new User();
        user.setUserId(userId);
        user.setPic(userInfoParam.getAvatarUrl());
        user.setNickName(EmojiUtil.toAlias(userInfoParam.getNickName()));
        userService.updateById(user);
//        String cacheKey = App.MINI.value() + StrUtil.COLON + SecurityUtils.getUser().getBizUserId();
//        cacheManagerUtil.evictCache("shop_user", cacheKey);
        return ResponseEntity.ok(null);
    }

    /**
     * 退出登录,并清除redis中的token
     **/
    @GetMapping("/logout")
    public Boolean removeToken(HttpServletRequest httpRequest) {
        String authorization = httpRequest.getHeader("authorization");
        String token = authorization.replace("bearer", "");
        return consumerTokenServices.revokeToken(token);
    }

    /**
     * 查看用户接口
     */
    @GetMapping("/userInfoBal")
    @ApiOperation(value = "查看用户信息", notes = "根据用户ID（userId）获取用户信息")
    public Result userInfoBal() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getUserByUserId(userId);
        if(null == user.getBalance()){
            user.setBalance(new BigDecimal("0"));
        }
        UserMoney userDto = mapperFacade.map(user, UserMoney.class);
        return Result.success(userDto);
    }


    @PostMapping("/restPass")
    public Result restPass(@RequestBody UserPassword userPassword) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getUserByUserId(userId);
        if(null == user){
            return Result.success("修改失败");
        }
        User userEdit = new User();
        userEdit.setId(user.getId());
        String oriPass = EncryptionUtil.combinationEncryp(userPassword.getOriPassword());
        String loginPass = EncryptionUtil.combinationEncryp(userPassword.getLoginPassword());
        userEdit.setLoginPassword(loginPass);

        if(!oriPass.equals(user.getLoginPassword())){
            return Result.failure("原始密码不正确");
        }
        userService.updateById(userEdit);
        return Result.success("修改成功");
    }




}
